package com.cwd.arm.domain.job;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.schedulerx.worker.domain.JobContext;
import com.alibaba.schedulerx.worker.processor.JavaProcessor;
import com.alibaba.schedulerx.worker.processor.ProcessResult;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.cwd.arm.common.enums.MsgTypeEnum;
import com.cwd.arm.common.util.StringUtil;
import com.cwd.arm.domain.job.dto.MsgJobDto;
import com.cwd.arm.domain.service.msg.MsgAppService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

/**
 * 消息任务
 * Created by yan on 22-2-20.
 */
@Component
@Slf4j
public class MsgJob extends JavaProcessor {

    @Autowired
    private Map<String, MsgAppService> msgAppServiceMap;

    @Override
    public ProcessResult process(JobContext context) throws Exception {
        log.debug("start:MsgJob----------------------->");
        try{
            String jobParameters = context.getJobParameters();
            MsgJobDto msgJobDto = buildMsgJobDto(jobParameters);
            for(MsgTypeEnum msgTypeEnum : msgJobDto.getMsgTypeEnums()){
                MsgAppService msgAppService = msgAppServiceMap.get(msgTypeEnum.getCode());
                doJob(msgAppService,msgJobDto);
            }
            return new ProcessResult(true);
        }catch (Exception e){
            log.error("MsgJob:{}",e.getMessage(),e);
            return new ProcessResult(false,e.getMessage());
        }
    }

    @Transactional
    public void doJob(MsgAppService msgAppService,MsgJobDto msgJobDto) throws Exception{
        if(msgJobDto.getNeedCancelMsg()){
            msgAppService.cancelRateWarnMsg();
        }
        if(msgJobDto.getNeedAddMsg()){
            msgAppService.addRateWarnMsg();
        }
        if(msgJobDto.getNeedSendMsg()){
            msgAppService.sendMsg();
        }
    }

    private MsgJobDto buildMsgJobDto(String jobParameters) {
        MsgJobDto jobDto;
        if (StringUtils.isEmpty(jobParameters)) {
            jobDto = new MsgJobDto();
        } else {
            jobDto = JSONObject.parseObject(jobParameters, MsgJobDto.class);
        }
        if(jobDto.getMsgTypeEnums() == null){
            jobDto.setMsgTypeEnums( MsgTypeEnum.values());
        }
        return jobDto;
    }
}
